import { expect } from '@jest/globals';
import fse from 'fs-extra';
import path from 'path';

import { addOhPackageDps, buildOneHapAndCheckFile, commonFileOperation, readZipEntry } from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },
  modulesOption: [ModuleTemplateType.EmptyAbility, ModuleTemplateType.StaticLibrary]
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  // 1. 使application依赖staticLibrary
  const applicationPath = project.getModule('application').moduleRootPath();
  await addOhPackageDps(applicationPath, {
    'staticLibrary': '../staticLibrary'
  });

  // 2. 在application模块的index.ets文件中进行ets components引用
  await commonFileOperation(path.resolve(applicationPath, 'src/main/ets/pages/Index.ets'), async (buffer) => {
    let content = buffer.toString();
    content = content.replace('Text(this.message)', 'MainPage()\n        Text(this.message)');
    return `import { MainPage } from 'staticLibrary'\n\n ${content}`;
  });

  // 3. 构建application模块
  await buildOneHapAndCheckFile('application')(project, taskConfig, record);

  // 4. 查看hap包中index.ets文件中引用情况
  const files = await fse.readdir(path.resolve(applicationPath, 'build/default/outputs/default'));
  const hapPath = files.find(item => item.endsWith('.hap'));

  // eslint-disable-next-line max-len
  const content = await readZipEntry(path.resolve(applicationPath, `build/default/outputs/default/${hapPath}`), 'ets/sourceMaps.map');
  expect(content).toContain('staticLibrary/src/main/ets/components/mainpage/MainPage.ets');
};

// 将demo测试用例注册到测试用例中心
TestCaseBuilder.builder()
  .caseName('OPENLAB_AIDE_ZOS_Build_library_Dependence_HOS_api10_STAGE_007')
  .description('011、eTS工程，feature依赖ets共享模块_ets引用')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).build())
  .testFun(testFun)
  .load();
